<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/file/Image.class.php, $Author:  $ */

require_once 'File.class.php';

class file_Image extends CFile
{
    var $nH;
    var $nW;

    var $thumbLargeThenPic = false;

    function file_Image()
    {
        parent::CFile();
        $this->aLimits['PERMITTED_TYPES'] = App::getParam('image.types');
        $this->aLimits['FILE_MAX_SIZE']   = (App::getSetting('max_upload_size') * 1024);
        $this->aLimits['MAX_IMAGE_W']     = App::getSetting('upload_set_size_image');
        $this->aLimits['MAX_IMAGE_H']     = App::getSetting('upload_set_size_image');
        $this->aLimits['MIN_IMAGE_W']     = App::getParam('image.min_w');
        $this->aLimits['MIN_IMAGE_H']     = App::getParam('image.min_h');
    }

    function loadInfo($sPath)
    {
        if (!parent::loadInfo($sPath))
        {
            return false;
		}

        if ($aInfo = @getImageSize($this->sPath))
        {
            $aTypes = array('', 'gif', 'jpg', 'png', 'swf', 'psd', 'bmp', 'tiff', 'tiff', 'jpc', 'jp2', 'jpx', 'jb2', 'swc', 'iff', 'wbmp', 'xbm');
            $this->nW = $aInfo[0];
            $this->nH = $aInfo[1];
            $this->sType = $aTypes[$aInfo[2]];
            //PHP >= 4.3.0
            $this->sMimeType = $aInfo['mime'];
            return true;
        }
        return $this->_addError('image.unsupported_type', $this->getName());
    }

    function _checkLimits()
    {
        if (!parent::_checkLimits())
        {
            return false;
        }
        if ($this->aLimits['MAX_IMAGE_W'] and $this->nW > $this->aLimits['MAX_IMAGE_W'])
        {
            $this->_addError('image.max_w', $this->aLimits['MAX_IMAGE_W'] );
        }
        if ($this->aLimits['MIN_IMAGE_W'] and $this->nW < $this->aLimits['MIN_IMAGE_W'])
        {
            $this->_addError('image.min_w', $this->aLimits['MIN_IMAGE_W'] );
        }
        if ($this->aLimits['MAX_IMAGE_H'] and $this->nH > $this->aLimits['MAX_IMAGE_H'])
        {
            $this->_addError('image.max_h', $this->aLimits['MAX_IMAGE_H'] );
        }
        if ($this->aLimits['MIN_IMAGE_H'] and $this->nH < $this->aLimits['MIN_IMAGE_H'])
        {
            $this->_addError('image.min_h', $this->aLimits['MIN_IMAGE_H'] );
        }
        if ($this->aLimits['PERMITTED_TYPES'] and !in_array($this->sType, $this->aLimits['PERMITTED_TYPES']))
        {
            $this->_addError('image.unsupported_type');
        }
        return (sizeof($this->aErrors) == 0);
    }

    /** Adds watermark to current image file
     * @see http://www.sitepoint.com/article/watermark-images-php
     * @param string $sWmPath path to _PNG-8_ image with watermark
     * @return boolean
     */
    function addWatermark($sWmPath)
    {    	
    	$sExt = substr($sWmPath, -3, 3);
        if ($sExt == 'png')
        {
            $hWm = imageCreateFromPng($sWmPath);
        }
        elseif ($sExt == 'gif')
        {
            $hWm = imageCreateFromGif($sWmPath);
        }
        else
        {
            return false;
        }
        $nW   = imageSx($hWm);
        $nH   = imageSy($hWm);
        $hImg = $this->_createImg();

        $nDestX = 5;
        $nDestY = $this->nH - $nH - 5;
        imageCopyMerge($hImg, $hWm, $nDestX, $nDestY, 0, 0, $nW, $nH, 50);

        imageJpeg($hImg, $this->sPath);

        imageDestroy($hImg);
        imageDestroy($hWm);

        return true;
    }

    /** Returns image handler
    */
    function _createImg()
    {
        $hImg = 0;
        $aInfo = getimagesize($this->sPath);

        switch ($aInfo[2])
        {
            case 1:
                $hImg = @imageCreateFromGif($this->sPath);
                break;
            case 3:
                $hImg = @imageCreateFromPng($this->sPath);
                break;
            default:
                $hImg = @imageCreateFromJpeg($this->sPath);
			break;
        }

        return $hImg;
    }

    /** Resizes image and writes to file
     * @param int $sPath   destin image file
     * @param int $nMaxW   maximum width
     * @param int $nMaxH   maximum height
     * @param string $sDr   transformation driver code ( gd, im)
     * @param array $aDrParam   driver specific params ( e.g for IM path and quality)
     * @return float ratio in % beetwen full image and thumbnail
     */
    function makeThumbnail($sPath, $nMaxW, $nMaxH, $sDr='gd', $aDrParam=array())
    {    	
    	list($nNewW, $nNewH) = $this->_calcSize($nMaxW, $nMaxH);    	
    	$aInfo = getimagesize($this->sPath);    	

        if (($aInfo[0] <= $nMaxW) && ($aInfo[1] <=$nMaxH))
        {
        	@copy($this->sPath,$sPath);
        	return ($nNewW * $nNewH)/($this->nW * $this->nH);
        }        
        
        if ($this->imageMagicExist())
        {
            $sDr = 'im';
        }
        
        switch ($sDr)
        {
            case 'im': // ImageMagick
               if (!isset($aDrParam['path']))
               {
                   $aDrParam['path'] = App::getParam('image.im.path');
               }
               if (!isset($aDrParam['quality']))
               {
                   $aDrParam['quality'] = '70';
               }
               $sCmd = '';
               $sCmd .= '"'.$aDrParam['path'].'"';
               $sCmd .= ' -resize '.$nNewW.'x'.$nNewH;
               if (2 == $aInfo[2])
               {
                   $sCmd .= ' -quality '.$aDrParam['quality'];
               }
               if (1 == $aInfo[2])
               {
                   $sGifPath = substr($sPath, 0, strrpos($sPath, '.')).'.gif';
                   $sCmd .= ' "'.escapeshellcmd($this->sPath).'" "'.escapeshellcmd($sGifPath).'"';
               }
               else
               {
                   $sCmd .= ' "'.escapeshellcmd($this->sPath).'" "'.escapeshellcmd($sPath).'"';
               }
               App::executeCommand($sCmd);
               if (1 == $aInfo[2])
               {
                   rename($sGifPath, $sPath);
               }
               break;
            case 'gd': // GD
            default:
                $hFrm = $this->_createImg();
                $hTo = imagecreatetruecolor($nNewW, $nNewH);

		        if($this->thumbLargeThenPic===false && $this->nH<=$nNewH && $this->nW<=$nNewW)
		        {
					$hTo=$hFrm;
		        }
		        else
		        {
			    	if($hFrm)
			    	{
		            	imageCopyResampled($hTo, $hFrm, 0, 0, 0, 0, $nNewW, $nNewH, $this->nW, $this->nH);
		            }
		        }

                switch ($this->sType)
                {
                    case 'gif':
            			if(!$hTo)
            			{
            				@copy($this->sPath,$sPath);
            			}
            			else
            			{
	                        @imagegif($hTo, $sPath);
						}
			            break;
                    case 'png':
                        @imagepng($hTo, $sPath);
                        break;
                    default:
                        @imagejpeg($hTo, $sPath);
                }

               	@imageDestroy($hTo);
               	@imageDestroy($hFrm);
			break;
        }
        return ($nNewW * $nNewH)/($this->nW * $this->nH);
    }


    /** Calculates size for resizing.
     * @param int $nMaxW  maximum width
     * @param int $nMaxH  maximum height
     * @return array new size (width, height)
     * @see makeThumbnail()
     */
    function _calcSize($nMaxW, $nMaxH)
    {
        $w  = $nMaxW;
        $h  = $nMaxH;

        if ($this->nW > $nMaxW)
        {
            $w  = $nMaxW;
            $h  = floor($this->nH * $nMaxW/$this->nW);
            if ($h > $nMaxH)
            {
              $h  = $nMaxH;
              $w  = floor($this->nW * $nMaxH/$this->nH);
            }
        }
        elseif ($this->nH > $nMaxH)
        {
            $h  = $nMaxH;
            $w  = floor($this->nW * $nMaxH/$this->nH);
        }

        return array($w, $h);
    }

    /** Creates random image ( acc to params) and displays it
     * @static
     * @param $nLeft text left offset
     * @param text top offset
     */
    function displayRandom($sText='', $nW=245, $nH=75, $nLeft=25, $nTop=5, $aParam=array())
    {
        $bUseFont = (function_exists('imagettftext') ? true : false);
        if (!$bUseFont)
        {
        	$nW = ($nW-20);
        }

        $hImg = imageCreate($nW, $nH);

        $nBgColor  = imageColorAllocate($hImg, 255, 255, 255);
        $nTxtColor = imageColorAllocate($hImg, 0, 0, 0);

		if ($bUseFont)
		{
        	$noise_color = imagecolorallocate($hImg, 207, 181, 181);
        	$noise_color2 = imagecolorallocate($hImg, 207, 181, 181);
	      	$width = $nW;
	      	$height = $nH;
	      	if (function_exists('imagefilledellipse'))
	      	{
	      		for( $i=0; $i<($width*$height)/3; $i++ )
	      		{
	        		imagefilledellipse($hImg, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
	      		}
	      	}

	      	for( $i=0; $i<($width*$height)/150; $i++ )
	      	{
	        	imageline($hImg, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color2);
	      	}
		}

		$sFont = App::getParam('path') . "file/fonts/HECK.TTF";
        if (!$bUseFont || !file_exists($sFont))
        {
        	imagestring($hImg, 5, $nLeft, ($nTop-15),  $sText, $nTxtColor) or die();
        }
        else
        {        	
        	if (!@imagettftext($hImg, 20, 0, $nLeft, $nTop, $nTxtColor, $sFont, $sText))
        	{
        		imagedestroy($hImg);
        		$hImg = imageCreate($nW, $nH);
        		$nBgColor  = imageColorAllocate($hImg, 255, 255, 255);
        		$nTxtColor = imageColorAllocate($hImg, 0, 0, 0);
        		imagestring($hImg, 5, $nLeft, ($nTop-15),  $sText, $nTxtColor) or die();
        	}
        }

        header('Content-Type: image/jpeg');
        imagejpeg($hImg);
    }

    function _hex2RGB($sHex)
    {
        $iRed = substr($sHex, 0, 2);
        $iGreen = substr($sHex, 2, 2);
        $iBlue = substr($sHex, 4, 2);
        $iRed = hexdec($iRed);
        $iGreen = hexdec($iGreen);
        $iBlue = hexdec($iBlue);
        return array($iRed, $iBlue, $iGreen);
    }

    function addText($sText, $iTextSize = 12, $sTextColor = '000000', $iW = null, $iH = null)
    {
        if (($iW === null) && ($iH === null))
        {
            $iW = 5;
            $iH = $this->nH - $iTextSize - 5;
        }
        $hImg = $this->_createImg();
        list($iRed, $iGreen, $iBlue) = $this->_hex2RGB($sTextColor);
        $sTextColor = imagecolorallocate($hImg, $iRed, $iGreen, $iBlue);
        imagestring($hImg, 2, $iW, $iH, $sText, $sTextColor);
        switch ($this->sType)
        {
            case 'gif':
            case 'png':
                imagepng($hImg, $this->sPath);
                break;
            default:
                imagejpeg($hImg, $this->sPath);
        }
        imageDestroy($hImg);
    }

    function imageMagicExist()
    {
        if (App::getParam('image.im.use'))
        {
        	return true;
        }
    	
    	return false;
    }
}
?>